// WebSocket客户端
class WebSocketClient {
    constructor() {
        this.ws = null;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectInterval = 3000;
    }
    
    connect(userId = 'default_user') {
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const wsUrl = `${protocol}//${window.location.host}/ws?user_id=${userId}`;
        
        this.ws = new WebSocket(wsUrl);
        
        this.ws.onopen = () => {
            console.log('WebSocket连接已建立');
            this.reconnectAttempts = 0;
            this.onOpen();
        };
        
        this.ws.onmessage = (event) => {
            try {
                const message = JSON.parse(event.data);
                this.onMessage(message);
            } catch (error) {
                console.error('解析WebSocket消息失败:', error);
            }
        };
        
        this.ws.onclose = () => {
            console.log('WebSocket连接已关闭');
            this.onClose();
            this.attemptReconnect();
        };
        
        this.ws.onerror = (error) => {
            console.error('WebSocket错误:', error);
            this.onError(error);
        };
    }
    
    attemptReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
            
            setTimeout(() => {
                this.connect();
            }, this.reconnectInterval);
        } else {
            console.log('达到最大重连次数，停止重连');
        }
    }
    
    send(message) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify(message));
        } else {
            console.warn('WebSocket连接未打开，无法发送消息');
        }
    }
    
    close() {
        if (this.ws) {
            this.ws.close();
        }
    }
    
    // 事件回调函数，子类可以重写
    onOpen() {
        // 连接建立时的处理
    }
    
    onMessage(message) {
        // 接收到消息时的处理
        console.log('收到消息:', message);
    }
    
    onClose() {
        // 连接关闭时的处理
    }
    
    onError(error) {
        // 发生错误时的处理
        console.error('WebSocket错误:', error);
    }
}

// 全局WebSocket客户端实例
window.wsClient = new WebSocketClient();

